﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.EFCore;
using System.Reflection;

namespace XAF_EFCore_Sample.Module.EFCoreObjectSpaces;

public class CustomEFCoreNestedObjectSpace : EFCoreObjectSpace, INestedObjectSpace
{
    public IObjectSpace ParentObjectSpace { get; private set; }

    private static IEntityStore GetEntityStore(EFCoreObjectSpace objectSpace)
    {
        var entityStoreFieldInfo = typeof(EFCoreObjectSpace).GetField("entityStore", BindingFlags.Instance | BindingFlags.NonPublic);
        return entityStoreFieldInfo.GetValue(objectSpace) as IEntityStore;
    }

    public CustomEFCoreNestedObjectSpace(EFCoreObjectSpace parentObjectSpace)
        : base(parentObjectSpace.TypesInfo, GetEntityStore(parentObjectSpace), () => parentObjectSpace.DbContext)
    {
        ParentObjectSpace = parentObjectSpace;
    }

    protected override void DoCommit()
    {
    }

    public override void Dispose()
    {
        ParentObjectSpace = null;
        isDisposed = true;

        base.Dispose();

        GC.SuppressFinalize(this);
    }
}
